<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="编号" prop="number">
              <el-input v-model="queryParams.number" placeholder="请输入编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="使用日期" prop="useDate" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="使用类型" prop="useType">
              <el-select v-model="queryParams.useType" placeholder="请选择使用类型" clearable>
                <el-option v-for="dict in seal_use_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="审批状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择审批状态" clearable>
                <el-option v-for="dict in seal_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime" style="width: 308px">
              <el-date-picker
                v-model="createTimeRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <template v-if="!hasFinalPermission">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['administration:seal:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['administration:seal:edit']"
                >修改</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['administration:seal:remove']"
                >删除</el-button
              >
            </el-col>
          </template>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['administration:seal:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="sealList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="编号" align="center" prop="number" >
          <template #default="scope">
            <el-tooltip :content="scope.row.number" placement="top" :disabled="!scope.row.number">
              <span style="display: inline-block; width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                {{ scope.row.number }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="申请部门" align="center" prop="deptId">
          <template #default="scope">
            <el-tag type="primary" disable-transitions>
              {{ scope.row.deptName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="项目名称" align="center" prop="proId">
           <template #default="scope">
            <el-tooltip :content="scope.row.proName" placement="top" :disabled="!scope.row.proName">
              <span style="display: inline-block; width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                {{ scope.row.proName }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="使用日期" align="center" prop="useDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.useDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="使用类型" align="center" prop="useType">
          <template #default="scope">
            <dict-tag :options="seal_use_type" :value="scope.row.useType" />
          </template>
        </el-table-column>
        <el-table-column label="印章类型" align="center" prop="sealType" width="200px">
          <template #default="scope">
            <div class="flex flex-wrap gap-1 justify-center">
              <el-tag 
                v-for="sealType in parseSealTypes(scope.row.sealType)"
                :key="sealType"
                type="primary"
                disable-transitions
                class="mb-1"
              >
                {{ getSealTypeName(sealType) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="审批状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="seal_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <template v-if="!hasFinalPermission">
              <el-tooltip content="修改" placement="top" v-if="scope.row.applyId === currentUserId && ['0', '3', '4'].includes(scope.row.status)">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['administration:seal:edit']"></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" v-if="scope.row.applyId === currentUserId && scope.row.status === '0'">
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['administration:seal:remove']"></el-button>
              </el-tooltip>
              <el-tooltip content="部门审核" placement="top" v-if="!['2', '4'].includes(scope.row.status)">
                <el-button
                  link
                  type="primary"
                  icon="CircleCheck"
                  @click="handleAudit(scope.row)"
                  v-hasPermi="['administration:seal:audit']"
                ></el-button>
              </el-tooltip>
            </template>
            <el-tooltip content="董办审核" placement="top" v-if="['1', '2', '4'].includes(scope.row.status)">
              <el-button
                link
                type="primary"
                icon="CircleCheck"
                @click="handleFinalAudit(scope.row)"
                v-hasPermi="['administration:seal:final']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改公章管理对话框 -->
    <seal-form v-model:visible="dialog.visible" :title="dialog.title" @success="getList" ref="sealFormRef" />
    <!-- 审核详情弹窗 -->
    <!-- <seal-audit
      ref="sealAuditRef"
      :visible="auditDialogVisible"
      title="公章管理审核流程"
      :seal-id="currentAuditId"
      :seal-status="seal_status"
      :seal-use-type="seal_use_type"
      @update:visible="auditDialogVisible = $event"
      @success="getList"
    /> -->

    <!-- 添加审核流程相关组件 -->
    <ApprovalFlow
      v-model:visible="auditDialogVisible"
      :business-type="'ADM-SEAL-AUDIT'"
      :business-id="Number(currentAuditId)"
      title="公章管理审核流程"
      @confirm="handleApprovalFlowConfirm"
      @cancel="handleApprovalFlowCancel"
      @template-imported="handleTemplateImported"
    />
  </div>
</template>

<script setup name="Seal" lang="ts">
import { useRoute, useRouter } from 'vue-router';
import { listSeal, getSeal, delSeal } from '@/api/general/administration/seal';
import type { SealVO, SealQuery } from '@/api/general/administration/seal/types';
import type { FormInstance } from 'element-plus';
import SealForm from './SealForm.vue';
import { useUserStore } from '@/store/modules/user';
import { getDept, listDept } from '@/api/system/dept';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { seal_status, seal_use_type } = toRefs<any>(proxy?.useDict('seal_status', 'seal_use_type'));

const route = useRoute();
const router = useRouter();
const sealList = ref<SealVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<FormInstance>();
const sealFormRef = ref();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const data = reactive<{
  queryParams: {
    pageNum: number;
    pageSize: number;
    number?: string;
    deptId?: string | number;
    useType?: string;
    status?: string;
    params: {
      bUseTime?: string; // 使用开始时间
      eUseTime?: string; // 使用结束时间
      beginTime?: string; // 创建开始时间
      endTime?: string; // 创建结束时间
    };
  };
}>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    number: undefined,
    deptId: undefined,
    useType: undefined,
    status: undefined,
    params: {
      bUseTime: undefined,
      eUseTime: undefined,
      beginTime: undefined,
      endTime: undefined
    }
  }
});

const { queryParams } = toRefs(data);

const userStore = useUserStore();
const currentUserId = userStore.userId;

const auditDialogVisible = ref(false);
const currentAuditId = ref<string | number>('');
const sealAuditRef = ref();

const hasFinalPermission = computed(() => {
  const permissions = useUserStore().permissions;
  return permissions.includes('administration:seal:final');
});

const hasAuditPermission = computed(() => {
  const permissions = useUserStore().permissions;
  return permissions.includes('administration:seal:audit');
});

const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createTimeRange = ref<[DateModelType, DateModelType]>(['', '']);

//印章类型配置项
const sealTypeOptions = ['公章', '财务章', '法人章', '测绘资质章', '其它'] as const;
const sealTypeMap = {
  '1': '公章',
  '2': '财务章', 
  '3': '法人章',
  '4': '测绘资质章',
  '5': '其它'
} as const;

/** 查询公章管理列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = { ...queryParams.value };
    if (dateRange.value?.length === 2) {
      params.params = {
        ...params.params,
        bUseTime: dateRange.value[0]?.toString(),
        eUseTime: dateRange.value[1]?.toString()
      };
    }
    if (createTimeRange.value?.length === 2) {
      params.params = {
        ...params.params,
        beginTime: createTimeRange.value[0]?.toString(),
        endTime: createTimeRange.value[1]?.toString()
      };
    }
    const res = await listSeal(params);
    sealList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取列表失败:', error);
    proxy?.$modal.msgError('获取列表失败');
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  createTimeRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.params = {
    bUseTime: undefined,
    eUseTime: undefined,
    beginTime: undefined,
    endTime: undefined
  };
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: SealVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  sealFormRef.value?.reset();
  dialog.visible = true;
  dialog.title = '印章使用申请';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SealVO) => {
  const _id = row?.id || ids.value[0];
  try {
    const res = await getSeal(_id);
    sealFormRef.value.openDialog(res.data);
    dialog.visible = true;
    dialog.title = '修改印章使用申请';
  } catch (error) {
    console.error('获取详情失败:', error);
    proxy?.$modal.msgError('获取详情失败');
  }
};

/** 删除按钮操作 */
const handleDelete = async (row?: SealVO) => {
  const _ids = row?.id || ids.value;
  try {
    await proxy?.$modal.confirm('是否确认删除公章管理编号为"' + _ids + '"的数据项？');
    await delSeal(_ids);
    proxy?.$modal.msgSuccess('删除成功');
    await getList();
  } catch (error) {
    console.error('删除失败:', error);
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'adm/seal/export',
    {
      ...queryParams.value
    },
    `seal_${new Date().getTime()}.xlsx`
  );
};

/** 部门审核按钮操作 */
const handleAudit = (row: SealVO) => {
  currentAuditId.value = row.id;
  auditDialogVisible.value = true;
  sealAuditRef.value?.openDialog(row.id, 'dept');
};

/** 董办审核按钮操作 */
const handleFinalAudit = (row: SealVO) => {
  currentAuditId.value = row.id;
  auditDialogVisible.value = true;
  sealAuditRef.value?.openDialog(row.id, 'ceo');
};

/**
 * 审核流程相关处理
 */
const handleApprovalFlowConfirm = (data: any) => {
  ElMessage.success('项目计划提交成功');
  auditDialogVisible.value = false;
  router.back();
};

/**
 * 解析多个印章类型
 */
const parseSealTypes = (sealTypeValue: string | string[]): string[] => {
  if (!sealTypeValue) return [];
  // 如果是数组直接返回
  if (Array.isArray(sealTypeValue)) {
    return sealTypeValue;
  }
  // 如果是逗号分隔的字符串
  if (typeof sealTypeValue === 'string') {
    // 支持多种分隔符：逗号、分号、空格等
    return sealTypeValue.split(/[,，;；\s]+/).filter(item => item.trim() !== '');
  }
  return [sealTypeValue];
};

/**
 * 获取印章类型名称（基于已有的 sealTypeMap）
 */
const getSealTypeName = (type: string) => {
  return sealTypeMap[type as keyof typeof sealTypeMap] || type || '未知类型';
};

const handleApprovalFlowCancel = () => (auditDialogVisible.value = false);

const handleTemplateImported = (data: any) => {
  ElMessage.success(`审核模板"${data.templateName}"导入成功`);
};

onMounted(() => {
  getList();
});
</script>
